// 引入创建slice对象的createSlice(slice集成了action和reducer)
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

//定义执行异步的函数.要求返回值是一个promise
export const asyncUpdMsg = createAsyncThunk('count/asyncUpdMsg', () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('哈哈哈哈')
      // reject('nonono')
    }, 1000)
  })
})

// 创建slice
export const countSlice = createSlice({
  name: 'countSlice', //slice的名称
  initialState: {
    count: 0,
    msg: 'hello',
  }, // 初始化数据
  // 创建reducer
  reducers: {
    // 创建同步action
    add: function (state) {
      // @reduxjs/toolkit支持直接修改state数据
      state.count = state.count + 1
    },
    sub: (state, action) => {
      // 在@reduxjs/toolkit中action中传入的数据,属性名统一写成payload
      state.count = state.count - action.payload
    },
  },
  // 为异步操作定义action
  extraReducers(builder) {
    builder.addCase(asyncUpdMsg.pending, (state, action) => {
      console.log('正在异步操作')
    })
    builder.addCase(asyncUpdMsg.fulfilled, (state, action) => {
      console.log('成功', state, action)
      state.msg = action.payload
    })
    builder.addCase(asyncUpdMsg.rejected, (state, action) => {
      console.log('失败')
    })
  },
})

// 也可以将action单独导出去
export const { add, sub } = countSlice.actions
